package com.liqy.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.liqy.api.cache.RouterCache;
import com.liqy.api.domain.Response;
import com.liqy.api.util.GroovyScriptFactory;
import com.liqy.api.util.ServletUtil;
import groovy.lang.Binding;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 脚本内存管理
 */
@Slf4j
@RestController
@RequestMapping("script/**")
public class ScriptController {

    @Value("${apiDemo.api.context}")
    String apiContext;

    @Autowired
    RouterCache cacheManager;

    @Autowired
    GroovyScriptFactory groovyScriptFactory;

    /*@Autowired
    RouterConfigService routerConfigService;*/

    @RequestMapping
    public Response runScript(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String servletPath = request.getRequestURI();
        servletPath = servletPath.substring("/script".length());
        log.info(String.format("groovy script exec: %s", servletPath));
        Object scriptStr = cacheManager.get(servletPath);
        if (scriptStr == null) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return Response.errResponse("Api not exists");
        }

        JSONObject args = ServletUtil.getRequestJson(request);
        Object o = groovyScriptFactory.scriptGetAndRun(String.valueOf(scriptStr), new Binding(args));
        return Response.successResponse("doSuccess", String.valueOf(o));
    }

}
